<template>
  <div class="app-container">

    <div class="custom_card_0">
      <el-form ref="queryForm" :inline="true" label-width="68px">

        <el-form-item label="门店" prop="ctripStoreName">
          <el-input v-model="ctripStoreName" clearable style="width:220px" placeholder="请输入门店"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card class="box-card" body-style="">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane v-for="(item, index) in tabList" :key="item.dictValue" :label="item.dictLabel" :name="item.dictValue">

          <el-table v-loading="loading" max-height="400px" :data="datadetail[item.dictValue].datalist" border
                    :header-cell-style="{background:'#F5F7FA'}">
            <el-table-column label="序号" width="100px" align="center">
              <template v-slot="scope">
                {{scope.$index+1+(datadetail[item.dictValue].pageNum-1)*datadetail[item.dictValue].pageSize}}
              </template>
            </el-table-column>
            <el-table-column label="OTA平台门店" align="center" prop="ctripStoreName">
            </el-table-column>

            <el-table-column label="门店匹配" align="center" prop="storeId">
              <template v-slot="scope">
                <el-select
                  v-model="scope.row.storeId"
                  filterable clearable
                  placeholder="请选择">

                  <el-option
                    v-for="item in options"
                    :key="item.storeId"
                    :label="item.storeName"
                    :value="item.storeId">
                  </el-option>
                </el-select>

              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="datadetail[item.dictValue].total>0"
            :total="datadetail[item.dictValue].total"
            :page.sync="datadetail[item.dictValue].pageNum"
            :limit.sync="datadetail[item.dictValue].pageSize"
            @pagination="getList(null)"
          />

        </el-tab-pane>
      </el-tabs>

      <div class="bottom-layout">
        <el-button type="primary" @click="confirm">门店同步</el-button>
      </div>
    </el-card>





  </div>
</template>

<script>

import {getAllStore, otactripsave, otastorelist} from "@/api/ota/ctrip";

export default {
  data() {
    return {
      loading: false,
      datadetail: {},
      tabList: [
        //   {
        //   name: '携程'
        // }, {
        //   name: '租租车'
        // }, {
        //   name: '哈啰'
        // }, {
        //   name: '悟空'
        // },
      ],
      options: [],
      ctripStoreName:null,
      activeName:null,
    };
  },
  computed: {
    // activeName: {
    //   get() {
    //     return this.tabList[0]&&this.tabList[0].dictValue||''
    //   },
    //   set(newVal) {
    //     return newVal
    //   }
    // }
  },

  async created() {

  },

  async mounted() {
    this.tabList = await this.getDict();

    for (const tab of this.tabList) {
      tab.dictValue = String(tab.dictValue)
      this.datadetail[tab.dictValue] = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        datalist: [],
        first: true,
        selList: []
      }
    }
    this.activeName = this.tabList[0].dictValue

    await this.getList(this.activeName)
    await this.getModelData();
  },

  methods: {

    getDict(){

      return new Promise(resolve => {
        this.getDicts("ota_order_resource").then(response => {
          resolve(response.data)
        });
      })

    },

    getList(name) {
      this.loading = true;
      let _this = this

      let requestName = name || _this.activeName

      _this.datadetail[requestName].selList = _this.datadetail[requestName].selList.concat(_this.datadetail[requestName].datalist)
      _this.datadetail[requestName].selList = _this.removeRepeat(_this.datadetail[requestName].selList, 'ctripStoreName')


      otastorelist(
        {
          orderSourceCode: requestName,
          ctripStoreName:this.ctripStoreName,
          pageNum: _this.datadetail[requestName].pageNum,
          pageSize: _this.datadetail[requestName].pageSize,
        }
      ).then(res => {
        _this.datadetail[requestName].datalist = res.rows
        _this.datadetail[requestName].total = res.total
        _this.datadetail[requestName].first = false

        for (const item of _this.datadetail[requestName].datalist) {
          for (const itemElement of _this.datadetail[requestName].selList) {
            if (item.ctripStoreName === itemElement.ctripStoreName) {
              item.storeId = itemElement.storeId
              break
            }
          }
        }


        this.loading = false;
      }).catch(e => {
        this.loading = false;
      })

    },

    getModelData() {
      getAllStore().then(res => {
        this.options = res.data
      })
    },

    handleClick(tab, event) {
      this.activeName = this.tabList[tab.index].dictValue
      if (tab.index > 0 && this.datadetail[this.tabList[tab.index].dictValue].first) {
        this.getList(this.activeName)
      }
    },

    cancel() {
      this.$emit('cancel')
    },

    removeRepeat(arr, name) {   //arr是传入的对象数组，name是根据去重的key
      let hash={}   //创建一个空对象，来保存需要的index
      return arr.reduce((acc, cru,index)=> {  //reduce()方法，功能是累加，第一个参数是累加起来的值，cru第二个参数，是数组遍历的其中一个元素，第三个参数是遍历的当前元素的索引
        if (!hash[cru[name]]) {  //判断hash[cru[name]]是否含有值，如果没有，则用hash[cru[name]]保存当前遍历元素的索引
          hash[cru[name]]={index:index}
          acc.push(cru)
        }else{//如果有值,说明重复，则通过保存的hash[cru[name]]去重
          acc.splice(hash[cru[name]]['index'],1,cru)
        }
        return acc;
      }, []);
    },

    confirm() {
      this.loading = true;

      let _this = this

      for (const key in this.datadetail) {
        this.datadetail[key].selList =
          this.datadetail[key].selList.concat(this.datadetail[key].datalist)

        this.datadetail[key].selList = _this.removeRepeat(this.datadetail[key].selList, 'ctripStoreName')
      }

      const list = []
      for (const key in this.datadetail) {
        if (this.datadetail[key].selList !== null && this.datadetail[key].selList.length > 0) {
          this.datadetail[key].selList.forEach(i => {
            let item = {
              id: i.id,
              ctripStoreId: i.ctripStoreId,
              vehiclectripStoreNameName: i.ctripStoreName,
              orderSource: i.orderSource,
              orderSourceCode: i.orderSourceCode,
              storeId: i.storeId
            }
            list.push(item)
          })
        }
      }

      otactripsave(list).then(res => {
        this.$message({
          message: '同步成功',
          type: 'success'
        });
        this.loading = false;
        this.$emit('success')
      }).catch(e => {
        this.loading = false;
      })

    },

    handleQuery(){
      this.datadetail[this.activeName].pageNum = 1
      this.getList(this.activeName)
    },
    resetQuery(){
      this.ctripStoreName = null;
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },

  }
};
</script>

<style scoped>

.app-container {
  display: flex;
  flex-direction: column;
}


.bottom-layout {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin: 30px 0 0;
}

</style>
